import React, { useState, useEffect } from 'react'
import { Outlet, useLocation, useNavigate } from 'react-router-dom'
import { getMenusApi } from '../../apis/user'
import { Layout, Menu, theme, Dropdown, Space, Modal } from 'antd'
import { MenuFoldOutlined, MenuUnfoldOutlined, UserOutlined, KeyOutlined, SettingOutlined, PoweroffOutlined, ExclamationCircleFilled } from '@ant-design/icons'
const { Header, Sider, Content } = Layout
const {confirm} = Modal
import '../../assets/styles/reset.css';

export default function Navpage() {
  const token = localStorage.token
    if(!token){
      window.location.hash = '#/login'
    }



  const [menus, setMenus] = useState([])
  useEffect(() => {
    // 获取侧边栏菜单
    async function getMenus() {
      const res = await getMenusApi()
      console.log(res[0].children);
      setMenus(handleMenus(res[0].children))
    }


    getMenus()
  }, [])

  // 处理侧边菜单栏
  
  function handleMenus(menus) {
    return menus.map(item => {
      const o = {
        title: item.name,
        label: item.name,
        key: item.path,
      }
      if (item.children) {
        o.children = handleMenus(item.children);
      }
      if (item.icon) {
        o.icon = <i className={'iconfont iconfont-' + item.icon} />;
      }
      return o;
    })
  }


  
  const [collapsed, setCollapsed] = useState(false);
  const {
    token: { colorBgContainer },
  } = theme.useToken();

  // 点击菜单切换
  const navigate = useNavigate()
  const location = useLocation()
  function clickMenu(params) {
    navigate(`${params.key}`)
    console.log(params);
    const subMenuKey = params.keyPath[1]
    if (subMenuKey) {
      sessionStorage.subMenuKey = subMenuKey
    } else {
      sessionStorage.removeItem("subMenuKey")
    }
  }
  const { avatar, username } = JSON.parse(localStorage.user)

  // 下拉菜单
  const items = [
    {
      key: '1',
      label: (
        <a  rel="noopener noreferrer" href='http://127.0.0.1:5173/#/profile'>个人中心</a>
      ),
      icon:<UserOutlined />
    },
    {
      key: '2',
      label: (
        <span  rel="noopener noreferrer">修改密码</span>
      ),
      icon:<KeyOutlined />
    },
    {
      key: '3',
      label: (
        <span  rel="noopener noreferrer">系统定制</span>
      ),
      icon:<SettingOutlined />
    },
    {
      key: '4',
      label: (
        <span  rel="noopener noreferrer" onClick={logOut}>退出登录</span>
      ),
      icon:<PoweroffOutlined />
    },

    
  ]

  // 退出登录
  function logOut(){
    confirm({
      title: "提示",

      icon: <ExclamationCircleFilled />,
      content: '您确定要退出登录吗？',
      onOk() {
          localStorage.clear();//清空本地存储
          navigate("/login", { replace: true })
          console.log('OK');
      },
      onCancel() {
          console.log('Cancel');
      },

  });
  }
  return (
    <Layout>
      <Sider trigger={null} collapsible collapsed={collapsed} style={{ height: '100vh' }}>
        <div style={{ margin: '20px 0' }}>
          <img src="http://xawn.f3322.net:8002/distremote/static/img/logo.png" style={{ marginLeft: '20px' }} />
          <h2 style={{ color: '#fff', float: 'right', marginRight: '50px', fontSize:'18px' }}>赤兔养车</h2>
        </div>
        <Menu
          theme="dark"
          mode="inline"
          selectedKeys={[location.pathname]}
          defaultOpenKeys={[sessionStorage.subMenuKey]}
          items={menus}
          onClick={clickMenu}
        />
      </Sider>
      <Layout className="site-layout">
        <Header style={{ padding: 0, background: colorBgContainer, display: 'flex', justifyContent: 'space-between' }}>
          {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
            className: 'trigger',
            onClick: () => setCollapsed(!collapsed),
          })}
          <Dropdown menu={{ items, }}>
            <a onClick={(e) => e.preventDefault()}>
              <Space>
                <div style={{ display: 'flex', alignItems: "center", marginRight: '30px' }}>
                  <img src={"http://xawn.f3322.net:8002/distremote/static/avatar/" + avatar} style={{ width: 40, height: 40, borderRadius: 50, marginRight: 15 }} />
                  <span>{username}</span>
                </div>
              </Space>
            </a>
          </Dropdown>

        </Header>
        <Content
          style={{
            margin: '24px 16px',
            padding: 24,
            minHeight: 280,
            background: colorBgContainer,
          }}
        >
          <Outlet />
        </Content>
      </Layout>
    </Layout>
  )
}
